package com.ziyueyuwen.xiniao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.JsonUtil;
import com.suyeer.basic.util.LogUtil;
import com.ziyueyuwen.xiniao.bean.homework.*;
import com.ziyueyuwen.xiniao.dao.ZyHomeworkRecordMapper;
import com.ziyueyuwen.xiniao.dao.ZySubjectQuestionMapper;
import com.ziyueyuwen.xiniao.enums.HomeworkStatusEnum;
import com.ziyueyuwen.xiniao.service.HomeworkRecordService;
import com.ziyueyuwen.xiniao.service.LessonService;
import com.ziyueyuwen.xiniao.service.SubjectQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jun 2018/12/22.
 */
@Service
public class HomeworkRecordServiceImpl implements HomeworkRecordService {

    @Autowired
    private ZyHomeworkRecordMapper zyHomeworkRecordMapper;

    @Autowired
    private ZySubjectQuestionMapper zySubjectQuestionMapper;

    @Autowired
    private LessonService lessonService;

    @Autowired
    private SubjectQuestionService subjectQuestionService;

    @Override
    public Boolean add(ZyHomeworkRecordDO zyHomeworkRecord) {
        return zyHomeworkRecordMapper.add(zyHomeworkRecord);
    }

    @Override
    public Boolean updateStudentAnswer(Integer id, List<AnswerData> answerInfoList) {
        return zyHomeworkRecordMapper.updateStudentAnswer(id, answerInfoList);
    }

    @Override
    public ZyHomeworkRecordDO getById(Integer id) {
        return zyHomeworkRecordMapper.getById(id);
    }

    @Override
    public ZyHomeworkRecordDO getByStudentIdAndLessonId(String studentId, Integer lessonId) {
        return zyHomeworkRecordMapper.getByStudentIdAndLessonId(studentId, lessonId);
    }

    @Override
    public List<ZyHomeworkRecordDO> listByClassId(Integer classId) {
        return zyHomeworkRecordMapper.listByClassId(classId);
    }

    @Override
    public Boolean finisHomework(Integer id) {
        return zyHomeworkRecordMapper.finisHomework(id);
    }

    @Override
    public List<HomeworkRecordNotMarkVO> listHomeworkRecordNotMark(String userId) {
        return zyHomeworkRecordMapper.listHomeworkRecordNotMark(userId);
    }

    @Override
    public Boolean markHomeworkRecord(Integer id, HomeworkMarkData markInfo, List<AnswerData> answerInfoList) {
        return zyHomeworkRecordMapper.markHomeworkRecord(id, markInfo, answerInfoList);
    }

    @Override
    public HomeworkRecordStatusDO getHomeworkStatus(String studentId, Integer lessonId) {
        ZyHomeworkRecordDO homeworkStatus = zyHomeworkRecordMapper.getHomeworkStatus(studentId, lessonId);
        HomeworkRecordStatusDO res = new HomeworkRecordStatusDO();
        if (homeworkStatus == null) {
            return res;
        }
        res.setHomeworkRecordId(homeworkStatus.getId())
                .setIfMark(homeworkStatus.getIfMarked());
        if (homeworkStatus.getIfFinishAnswer() == null) {
            res.setStatus(HomeworkStatusEnum.NOT_START);
            return res;
        }
        if (homeworkStatus.getIfFinishAnswer()) {
            res.setStatus(HomeworkStatusEnum.FINISHED);
        } else {
            res.setStatus(HomeworkStatusEnum.NOT_FINISH);
        }
        return res;
    }

    @Override
    public List<ZyHomeworkRecordDO> getByCourseIdAndLessonIndex(Integer courseId, Integer lessonIndex) {
        return zyHomeworkRecordMapper.getByCourseIdAndLessonIndex(courseId, lessonIndex);
    }

    @Override
    public void saveClassroomTestRecord(Integer eeoClassId, Integer subjectQuestionId, Integer testNum, Integer questionSize, String dataStr) {
        IdInfoData idInfoData = zySubjectQuestionMapper.getIdInfoByEeoClassId(eeoClassId);
        JSONArray recordArr = JSON.parseArray(dataStr);
        for (int i = 0; i < recordArr.size(); i++) {
            try {
                JSONObject itemObj = recordArr.getJSONObject(i);
                itemObj.put("questionSize", questionSize);
                String studentId = itemObj.getString("account");
                ZyHomeworkRecordDO record = getByStudentIdAndLessonId(studentId, idInfoData.getLessonId());
                if (record == null) {
                    record = new ZyHomeworkRecordDO();
                    record.setClassId(idInfoData.getClassId());
                    record.setLessonId(idInfoData.getLessonId());
                    record.setCourseId(idInfoData.getCourseId());
                    record.setStudentId(studentId);
                    record.setSubjectQuestionId(subjectQuestionId);
                    record.setAnswerInfoList(new ArrayList<>());
                    record.setIfFinishAnswer(false);
                    record.setIfMarked(false);
                    add(record);
                }
                record.getClassroomTestRecord().put(testNum.toString(), itemObj);
                zyHomeworkRecordMapper.updateClassroomTestRecord(record.getId(), record.getClassroomTestRecord());
            } catch (Exception e) {
                LogUtil.error(e);
            }
        }
    }

    @Override
    public ClassroomTestRecordDataDTO getData4ClassroomTestReport(String studentAccount, Integer lessonId) {
        IdInfoData idInfoData = zySubjectQuestionMapper.getIdInfoByLessonId(lessonId);
        ZySubjectQuestionDO subjectQuestion = zySubjectQuestionMapper.getBySubjectIdAndHomeworkIndex(idInfoData.getSubjectId(), idInfoData.getLessonIndex());
        ClassroomTestRecordDataDTO classroomTestReport = JsonUtil.changeType(subjectQuestion.getRemarkInfo(), ClassroomTestRecordDataDTO.class);
        ZyHomeworkRecordDO record = getByStudentIdAndLessonId(studentAccount, lessonId);
        if (record != null && record.getClassroomTestRecord() != null) {
            JSONObject classroomTestRecord = record.getClassroomTestRecord();
            Integer totalQuestionNum = 0;
            Integer totalCorrectQuestionNum = 0;
            for (String key : classroomTestRecord.keySet()) {
                JSONObject itemObj = classroomTestRecord.getJSONObject(key);
                Integer questionSize = itemObj.getInteger("questionSize");
                totalQuestionNum += questionSize;
                Integer correctQuestionNum = 0;
                JSONObject answerArr = itemObj.getJSONObject("answers");
                Map<String, Object> answerMap = answerArr.getInnerMap();

                for (Map.Entry<String, Object> e : answerMap.entrySet()) {
                    JSONObject answerItem = (JSONObject) e.getValue();
                    if (answerItem.getBoolean("ifRight")) {
                        correctQuestionNum++;
                        totalCorrectQuestionNum++;
                    }
                }
                String itemRate = (100 * correctQuestionNum / questionSize) + " %";
                classroomTestReport.getPerRate().put(key, itemRate);
            }
            if (totalQuestionNum > 0) {
                String totalRate = (100 * totalCorrectQuestionNum / totalQuestionNum) + " %";
                classroomTestReport.setTotalRate(totalRate);
            }
        }
        return classroomTestReport;
    }
}
